package com.campus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.entity.*;
import com.campus.entity.vo.CheckInUserVO;
import com.campus.mapper.BuildingMapper;
import com.campus.mapper.CheckInMapper;
import com.campus.mapper.DormitoryMapper;
import com.campus.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/checkin")
public class SignInController {

    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private DormitoryMapper dorminMapper;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private StudentMapper studentMapper;

    @RequestMapping("/{supervisor}")
    @Cacheable(value = "signIn")
    public ResultBody checkSignIn(@PathVariable("supervisor")String supervisor,Long l){
//        获取当前管理员是管理的那栋楼
        BuildingEntity admin = buildingMapper.selectOne(new QueryWrapper<BuildingEntity>().eq("building_admin", supervisor));
        if (admin==null){
//            TODO 返回未找到记录的错误

            return ResultBody.error();
        }
//        查询这栋楼所有的住户
        List<DormitoryEntity> residents = dorminMapper.selectList(new QueryWrapper<DormitoryEntity>().eq("building_no", admin.getBuildingNo()));

//        查看residents的用户信息
        List<String> collects = residents.stream().map(DormitoryEntity::getAccount).collect(Collectors.toList());
        List<Student> students = studentMapper.selectList(new QueryWrapper<Student>().in("account", collects));
//        获取当天哪些住户已经打卡
//        TODO 条件有误，未查到相关资料,应该查询某一天的打卡的所有人
        long t = 1000*60*60*24;
        List<String> checkedStudents = checkInMapper.selectList(new QueryWrapper<SignInEntity>().ge("date",new Date(l-l%t)))
                .stream().map(SignInEntity::getAccount).collect(Collectors.toList());

//        封装用户信息并分开未打开用户
        List<CheckInUserVO> studentInfos = students.stream().map((student) -> new CheckInUserVO(false, student)).collect(Collectors.toList());
        
        for (CheckInUserVO dto:studentInfos){
            if (checkedStudents.contains(dto.getStudentInfo().getAccount())){
                dto.setIsChecked(true);
            }
        }
        return ResultBody.ok().data("info",studentInfos);
    }

    @RequestMapping("/add")
    @CacheEvict(value="signIn", allEntries =true)
    public ResultBody addChecked(@RequestBody SignInEntity signIn){
        checkInMapper.insert(signIn);
        return ResultBody.ok().message("用户"+signIn.getAccount()+"打开成功");
    }
}
